import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gzx_dropdown_menu/gzx_dropdown_menu.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tender_flutter/constant/app_config.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/home/api/api_collection.dart';
import 'package:tender_flutter/page/home/api/api_home.dart';
import 'package:tender_flutter/page/home/item/certificate_list_cell.dart';
import 'package:tender_flutter/page/home/model/cer_category_entity.dart';
import 'package:tender_flutter/page/home/model/certification_entity.dart';
import 'package:tender_flutter/page/home/model/common_tag_model.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/widgets/drop_down_menu/drop_down_certificate_widget.dart';
import 'package:tender_flutter/widgets/drop_down_menu/drop_dpwm_list_widget.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';
import 'package:tender_flutter/widgets/search_app_bar.dart';

class CertificateSearchPage extends StatefulWidget {
  @override
  _CertificateSearchPageState createState() => _CertificateSearchPageState();
}

class _CertificateSearchPageState extends State<CertificateSearchPage> {
  List<String> _dropDownHeaderItemStrings = ['资质类别', '发证时间'];
  // CityEntity _selectCityModel;
  CerCategoryEntity _selectCerModel;
  CommonTagModel _selectTimeModel;
  GZXDropdownMenuController _dropdownMenuController =
      GZXDropdownMenuController();

  /// 刷新组件
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  LoadState _loadState = LoadState.State_Loading;

  Future<ApiResponse<CertificationListEntity>> _listFuture;

  Future<List<CerCategoryEntity>> _filterCerFuture;

  Future<List<CommonTagModel>> _filterTimesFuture;

  /// 资质类别数据
  List<CerCategoryEntity> _categoryDatas;

  /// 数据列表
  List<CertificationEntity> _dataLists = [];

  /// 搜搜关键词
  String _keyword;

  /// 页码
  int page = AppConfig.page;

  var _scaffoldKey = new GlobalKey<ScaffoldState>();
  GlobalKey _stackKey = GlobalKey();

  /// 收藏/取消
  /// 返回是否请求成功的状态
  Future<bool> _setCollection({String cerId}) async {
    var response = await ApiCollection.certificationCollection(cerId: cerId);
    ToastUtils.show(response.msg);
    return response.status == Status.SUCCESS ? true : false;
  }

  /// 获取时间
  Future<List<CommonTagModel>> _getTimes() async {
    return ApiHome.getFilterTimesDatas();
  }

  /// 获取资质类别
  Future<List<CerCategoryEntity>> _getCerCategory() async {
    if (_categoryDatas != null && !_categoryDatas.isNotEmpty) {
      return _categoryDatas;
    }
    var response =
        await ApiHome.getCertificateCategory<List<CerCategoryEntity>>();
    _categoryDatas = response.result;

    // for (CommonTagModel tagModel in _industryDatas) {
    //   tagModel.isSelected = false;
    // }
    // _industryDatas.insert(
    //     0, CommonTagModel(id: 0, name: "全部", value: "", isSelected: true));
    return _categoryDatas;
  }

  /// 获取数据
  Future<ApiResponse<CertificationListEntity>> _getData() async {
    var response = await ApiHome.getCertificateList<CertificationListEntity>(
        categoryId: _selectCerModel != null ? _selectCerModel.code : null,
        time: _selectTimeModel != null ? _selectTimeModel.value : null,
        companyName: _keyword,
        page: page);

    if (_refreshController.isLoading) {
      _refreshController.loadComplete();
    }
    if (_refreshController.isRefresh) {
      _refreshController.refreshCompleted();
    }
    return response;
  }

  /// 手动刷新数据
  void _manualRefersh() {
    if (_loadState == LoadState.State_Success && _refreshController != null) {
      _refreshController.requestRefresh();
    } else {
      _onRefresh();
    }
  }

  ///下拉刷新
  void _onRefresh() {
    page = 1;
    setState(() {
      _listFuture = _getData();
    });
  }

  /// 加载更多
  void _onLoading() {
    page += 1;
    setState(() {
      _listFuture = _getData();
    });
  }

  FutureBuilder<ApiResponse<CertificationListEntity>> _buildFutureBuilder() {
    return FutureBuilder(
        future: _listFuture,
        // ignore: missing_return
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<CertificationListEntity>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              CertificationListEntity entity = snapshot.data.result;
              if (snapshot.data.status == Status.SUCCESS) {
                List temps = entity.xList == null ? [] : entity.xList;
                page == AppConfig.page
                    ? _dataLists = temps
                    : _dataLists += temps;
                if (_dataLists.isEmpty) {
                  _loadState = LoadState.State_Empty;
                } else {
                  _loadState = LoadState.State_Success;
                }
              } else {
                _loadState = LoadState.State_Error;
              }
            } else if (snapshot.hasError) {
              _loadState = LoadState.State_Error;
            }

            /// 结束刷新，处理分页
            if (_dataLists.length % AppConfig.pageCount != 0) {
              _refreshController.loadNoData();
            } else {
              if (_refreshController.isLoading) {
                _refreshController.loadComplete();
              }
            }
            if (_refreshController.isRefresh) {
              _refreshController.refreshCompleted();
            }
          }

          return LoadStateLayout(
            state: _loadState,
            successWidget: _initContentListView(),
          );
        });
  }

  @override
  void initState() {
    super.initState();
    _filterCerFuture = _getCerCategory();
    _filterTimesFuture = _getTimes();
    _listFuture = _getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      backgroundColor: ThemeColors.colorWhite,
      appBar: _initAppBar(),
      body: _initBody(),
    );
  }

  /// 导航
  Widget _initAppBar() {
    return SearchAppBar(
      context,
      searchCallback: (value) {
        // 键盘消失
        FocusScope.of(context).requestFocus(FocusNode());
        _keyword = value;
        _refreshController.requestRefresh();
      },
    );
  }

  /// 筛选菜单
  Widget _initBody() {
    return Stack(
      key: _stackKey,
      children: <Widget>[
        Column(
          children: <Widget>[
            // 下拉菜单头部
            GZXDropDownHeader(
              height: ScreenAdapter.height(90),
              // 下拉的头部项，目前每一项，只能自定义显示的文字、图标、图标大小修改
              items: [
                GZXDropDownHeaderItem(_dropDownHeaderItemStrings[0]),
                GZXDropDownHeaderItem(_dropDownHeaderItemStrings[1]),
                // GZXDropDownHeaderItem(
                //   _dropDownHeaderItemStrings[2],
                // ),
              ],
              // GZXDropDownHeader对应第一父级Stack的key
              stackKey: _stackKey,
              // controller用于控制menu的显示或隐藏
              controller: _dropdownMenuController,
              // 当点击头部项的事件，在这里可以进行页面跳转或openEndDrawer
              onItemTap: (index) {
                // if (index == 3) {
                //   _dropdownMenuController.hide();
                //   _scaffoldKey.currentState.openEndDrawer();
                // }
              },
              // 文字样式
              style: TextStyle(
                  color: ThemeColors.colorType1,
                  fontSize: ScreenAdapter.sp(28)),
              // 下拉时文字样式
              dropDownStyle: TextStyle(
                fontSize: ScreenAdapter.sp(28),
                color: ThemeColors.colorType6,
              ),
              // 图标颜色
              iconColor: ThemeColors.colorType7,
              // 下拉时图标颜色
              iconDropDownColor: ThemeColors.colorType6,
            ),
            Expanded(
              child: _buildFutureBuilder(),
            ),
          ],
        ),
        // 下拉菜单
        GZXDropDownMenu(
          // controller用于控制menu的显示或隐藏
          controller: _dropdownMenuController,
          // 下拉菜单显示或隐藏动画时长
          animationMilliseconds: 300,
          dropdownMenuChanging: (isShow, index) {},
          dropdownMenuChanged: (isShow, index) {},
          menus: [
            // GZXDropdownMenuBuilder(
            //     dropDownHeight: 40 * 8.0,
            //     dropDownWidget: FutureBuilder(
            //         future: ApiCommon.getCityDatas(),
            //         builder: (BuildContext context,
            //             AsyncSnapshot<List<CityEntity>> snapshot) {
            //           if (snapshot.hasData) {
            //             return DropMenuAddressWidget(
            //               cityDatas: snapshot.data,
            //               selectCityCallback:
            //                   (levelIndex, itemIndex, cityModel) {
            //                 if (levelIndex == 1) {
            //                   _selectCityModel = cityModel;
            //                   _dropDownHeaderItemStrings[0] = cityModel.title;
            //                   _dropdownMenuController.hide();
            //                   _manualRefersh();
            //                 }
            //                 setState(() {});
            //               },
            //             );
            //           } else {
            //             return Container();
            //           }
            //         })),
            GZXDropdownMenuBuilder(
                dropDownHeight: 40 * 8.0,
                dropDownWidget: FutureBuilder(
                    future: _filterCerFuture,
                    builder: (BuildContext context,
                        AsyncSnapshot<List<CerCategoryEntity>> snapshot) {
                      if (snapshot.hasData) {
                        return DropMenuCertificateWidget(
                          categoryDatas: snapshot.data,
                          selectCerCallback: (levelIndex, itemIndex, cerModel) {
                            if (levelIndex == 1) {
                              _selectCerModel = cerModel;
                              _dropDownHeaderItemStrings[0] = cerModel.title;
                              _dropdownMenuController.hide();
                              _manualRefersh();
                            }
                            setState(() {});
                          },
                        );
                      } else {
                        return Container();
                      }
                    })),
            GZXDropdownMenuBuilder(
                dropDownHeight: ScreenAdapter.height(80) * 5,
                dropDownWidget: FutureBuilder(
                    future: _filterTimesFuture,
                    builder: (BuildContext context,
                        AsyncSnapshot<List<CommonTagModel>> snapshot) {
                      if (snapshot.hasData) {
                        return DropDownListWidget(
                          listDatas: snapshot.data,
                          selectListItemCallback: (itemIndex, tagModel) {
                            _selectTimeModel = tagModel;
                            _dropDownHeaderItemStrings[1] =
                                _selectTimeModel.title == '全部'
                                    ? '发证时间'
                                    : _selectTimeModel.title;
                            _dropdownMenuController.hide();
                            _manualRefersh();
                          },
                        );
                      } else {
                        return Container();
                      }
                    })),
          ],
        ),
      ],
    );
  }

  /// 主体内容列表
  Widget _initContentListView() {
    return SmartRefresher(
        controller: _refreshController,
        enablePullUp: true,
        enablePullDown: true,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: ListView.separated(
          itemCount: _dataLists.length,
          itemBuilder: (BuildContext context, int index) {
            CertificationEntity model = _dataLists[index];
            return CertificateListCell(
                data: model,
                keyword: _keyword,
                onCollection: () async {
                  return await _setCollection(cerId: model.key);
                },
                onTap: () {
                  LRouter.navigatorCtx(context).push(
                      Routes.certificateDetailPage,
                      arguments: CertificateDetailPageArguments(
                          certId: model.Id, companyName: model.CompanyName));
                });
          },
          separatorBuilder: (BuildContext context, int index) {
            return Divider(
              height: ScreenAdapter.height(10),
              color: ThemeColors.colorType49,
            );
          },
        ));
  }
}
